package com.weimob.cloud.api.config.impl;

import com.weimob.cloud.api.config.WeimobAccessTokenStorageConfig;
import com.weimob.cloud.api.token.rsp.WeimobAccessTokenRsp;

/**
 * 微盟 access token 默认存储实现类
 */
public class WeimobAccessTokenDefaultStorageConfigImpl implements WeimobAccessTokenStorageConfig {

    private static final Object LOCK = new Object();

    private volatile String accessToken;
    private volatile Long expiresTimestamp;

    @Override
    public String getAccessToken() {
        long currentTimestamp = System.currentTimeMillis();
        if (currentTimestamp < expiresTimestamp) {
            return accessToken;
        }
        return null;
    }

    @Override
    public void setAccessToken(WeimobAccessTokenRsp accessTokenRsp) {
        if (accessTokenRsp.getExpiresIn() < 5) {
            // token有效期太短，下次重新获取
            return;
        }

        synchronized (LOCK) {
            accessToken = accessTokenRsp.getAccessToken();
            expiresTimestamp = System.currentTimeMillis() + (accessTokenRsp.getExpiresIn() - 60) * 1000L;
        }
    }
}
